package com.springboot.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.springboot.demo.constant.RedisEnum;
import com.springboot.demo.domain.User;
import com.springboot.demo.service.RedisService;
import com.springboot.demo.service.UserService;
import com.springboot.demo.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private RedisService redisService;

    @GetMapping("/showUser/{userId}")
    @ResponseBody
    public User showUser(@PathVariable(name = "userId") int userId) {
        User user;
        String redisKey = RedisUtils.keyBuilder(RedisEnum.DEMO_DICTIONARY_ID, String.valueOf(userId));
        String result = redisService.get(redisKey);
        if (result == null) {
            user = this.userService.getUserById(userId);
            redisService.set(redisKey, JSONObject.toJSONString(user));
        } else {
            user = JSONObject.parseObject(result, User.class);
        }
        return user;
    }

    @GetMapping("/showListUser")
    @ResponseBody
    public List<User> showListUser() {
        List<User> userList;
        String redisKey = RedisUtils.keyBuilder(RedisEnum.DEMO_DICTIONARY_LIST, "ALL");
        String result = redisService.get(redisKey);
        if (result == null) {
            userList = userService.selectAllUser();
            redisService.set(redisKey, JSONObject.toJSONString(userList));
        } else {
            userList = JSONObject.parseArray(result, User.class);
        }
        return userList;
    }

    @ApiOperation(value = "用户欢迎")
    @GetMapping(value = "hello")
    @ResponseBody
    public String hello() {
        return "Hello UserController!";
    }

}
